package com.example.mvp.mvppromote.ui.activity;

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.transition.Slide;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;

import com.example.mvp.mvppromote.R;
import com.example.mvp.mvppromote.ui.fragment.BandFragment;
import com.example.mvp.mvppromote.ui.fragment.CustomViewFragment;
import com.example.mvp.mvppromote.ui.fragment.WeiXinFragment;
import com.example.mvp.mvppromote.utils.AppManager;
import com.example.mvp.mvppromote.utils.LogUtils;
import com.example.mvp.mvppromote.utils.RxBus;
import com.example.mvp.mvppromote.utils.RxBusEvent;
import com.example.mvp.mvppromote.utils.StatusBarUtil;
import com.example.mvp.mvppromote.utils.ToaskUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Subscription;
import rx.functions.Action1;


public class MainActivity extends AppCompatActivity implements
        NavigationView.OnNavigationItemSelectedListener {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.replace)
    FrameLayout replace;
    @BindView(R.id.ctl_main)
    CoordinatorLayout ctlMain;
    @BindView(R.id.nav_view)
    NavigationView navView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    private Fragment currentFragment;
    private ArrayList<Fragment> mFragments;
    private Subscription rxSub;
    private List<String> mTitles;
    private List<Integer> mIcons;
    private MenuItem mPreMenuItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        AppManager.getAppManager().addActivity(this);
        boolean isKitKat = Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT;
        if (isKitKat)
            ctlMain.setFitsSystemWindows(false);
        setToolBar(null, toolbar, true, false, drawerLayout);
        //改变statusBar颜色而DrawerLayout依然可以显示在StatusBar
        //ctlMain.setStatusBarBackgroundColor(setToolBar(toolbar,true,false,null));
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawerLayout, toolbar, R.string.navigation_drawer_open,
                R.string.navigation_drawer_close);
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();
        assert navView != null;
        navView.setNavigationItemSelectedListener(this);
        int[][] state = new int[][]{
                new int[]{-android.R.attr.state_checked}, // unchecked
                new int[]{android.R.attr.state_checked}  // pressed
        };
        int[] color = new int[]{
                Color.BLACK,
                ContextCompat.getColor(this, R.color.colorAccent)
        };

        navView.setItemTextColor(new ColorStateList(state, color));
        navView.setItemIconTintList(new ColorStateList(state, color));
        initMenu();
        rxSub = RxBus.getInstance().toObservable(RxBusEvent.class).subscribe(new Action1<RxBusEvent>() {
            @Override
            public void call(RxBusEvent rxBusEvent) {
            }
        });
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        assert drawer != null;
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    private void switchFragment(Fragment fragment, String title) {
        Slide slideTransition;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //Gravity.START部分机型崩溃java.lang.IllegalArgumentException: Invalid slide direction
            slideTransition = new Slide(Gravity.LEFT);
            slideTransition.setDuration(700);
            fragment.setEnterTransition(slideTransition);
            fragment.setExitTransition(slideTransition);
        }
        if (currentFragment == null || !currentFragment.getClass().getName().equals(fragment.getClass().getName())) {
            getSupportFragmentManager().beginTransaction().replace(R.id.replace, fragment).commit();
            currentFragment = fragment;
            ActionBar actionBar = getSupportActionBar();
            assert actionBar != null;
            actionBar.setTitle(title);
        }

    }


    private void initMenu() {
        mTitles = new ArrayList<>();
        mTitles.add("榜单热门");
        mTitles.add("微信精选");
        mTitles.add("自定义view");
        mFragments = new ArrayList<Fragment>();
        mFragments.add(new BandFragment());
        mFragments.add(new WeiXinFragment());
        mFragments.add(new CustomViewFragment());
        mIcons = new ArrayList<>();
        mIcons.add(R.drawable.icon_guokr);
        mIcons.add(R.drawable.icon_weixin);
        mIcons.add(R.drawable.icon_custom);
        Menu menu = navView.getMenu();
        menu.clear();
        for (int i = 0; i < mFragments.size(); i++) {
            MenuItem menuItem = menu.add(0, i, 0, mTitles.get(i));
            mTitles.add(mTitles.get(i));
            menuItem.setIcon(mIcons.get(i));
            menuItem.setCheckable(true);
            if (i == 0) {
                menuItem.setChecked(true);
            }
        }
        navView.inflateMenu(R.menu.activity_main_drawer);
        switchFragment(mFragments.get(0), mTitles.get(0));
    }

    public int setToolBar(FloatingActionButton floatingActionButton, Toolbar toolbar, boolean
            isChangeToolbar, boolean isChangeStatusBar, DrawerLayout drawerLayout) {
        int vibrantColor = 0;
        int mutedColor = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setNavigationBarColor(Color.BLACK);
        }
        if (floatingActionButton != null)
            floatingActionButton.setBackgroundTintList(ColorStateList.valueOf(mutedColor));
        if (isChangeToolbar)
            toolbar.setBackgroundColor(vibrantColor);
        if (isChangeStatusBar) {
            StatusBarUtil.setColor(this, vibrantColor);
        }
        if (drawerLayout != null) {
            StatusBarUtil.setColorForDrawerLayout(this, drawerLayout, vibrantColor);
        }
        return vibrantColor;
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        if (mPreMenuItem != null) mPreMenuItem.setChecked(false);
        item.setChecked(true);
        drawerLayout.closeDrawers();
        mPreMenuItem = item;
        int id = item.getItemId();
        if (id < mFragments.size()) {
            switchFragment(mFragments.get(id), mTitles.get(id));
        }
        switch (id) {
            case R.id.nav_setting:
                ToaskUtil.toastShort(this, "set");
                break;
            case R.id.nav_change:
                ToaskUtil.toastShort(this, "change");
                break;
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        assert drawer != null;
        drawer.closeDrawer(GravityCompat.START);
        return false;
    }
}
